package com.orcamento.security;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.orcamento.util.AppConfig;

public class CookieManager {
	
	private static final Log LOG = LogFactory.getLog(CookieManager.class);
	
	public static final String ACCOUNT_COOKIE = AppConfig.getAccountCookieName();
	
	private static final Integer MAX_AGE_COOKIE = 60*60*24*15; //15 dias
	private static final String PATH = "/";
	private static final String DOMAIN = AppConfig.getDomainCookie();
	
	public static Cookie getCookieByName(String name, HttpServletRequest request) {
		try {
			for(Cookie cookie : request.getCookies()) {
				if( name.equals( cookie.getName() ) ) {
					return cookie;
				}
			}
		} catch(Exception e) {
			LOG.info("Nao foi possivel encontrar o Cookie: " + name);
		}
		return null;
	}
	
	public static void addCookie(String name, String value, HttpServletResponse response) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge( MAX_AGE_COOKIE );
		cookie.setPath(PATH);
		cookie.setDomain(DOMAIN);
		response.addCookie(cookie);
	}
	
	public static void removeCookie(String name, HttpServletResponse response) {
		addCookie(name, "", response);
	}

	public static Long getAccountCookie(HttpServletRequest request) {
		Cookie cookie = getCookieByName(ACCOUNT_COOKIE, request);
		
		if(cookie == null || StringUtils.isBlank( cookie.getValue() )) {
			return null;
		}
		
		return Long.valueOf( cookie.getValue() );
	}
	
}
